﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SergioPereira.Xml;
using System.Xml.Linq;

namespace MonoRailRSS.Models
{
    public class FeedRepository : Repository<RSSFeed>, IFeedRepository
    {
        public IEnumerable<Post> GetPosts(RSSFeed feed)
        {
            var rssDoc = XDocument.Load(feed.FeedUrl);
            return from post
                   in rssDoc.Descendants("item")
                   select new Post() {
                       Title = post.Element("title").Value,
                       Content = post.Element("description").Value,
                       Author = post.Element(XName.Get("creator", "http://purl.org/dc/elements/1.1/")).Value,
                       Date = post.Element("pubDate").Value,
                       Link = post.Element("link").Value
                   };
        }

        protected override List<RSSFeed> TryReadItemsFromFile(string filename)
        {
            var file = XDocument.Load(filename);
            try
            {
                return (from xItem
                       in file.Descendants("feed")
                        select new RSSFeed()
                        {
                            Id = int.Parse(xItem.Attribute("id").Value),
                            Name = xItem.Attribute("name").Value,
                            FeedUrl = xItem.Attribute("url").Value,
                        }).ToList();

            }
            catch
            {
                return new List<RSSFeed>();
            }
        }

        protected override void WriteItemsFile(string filename, IEnumerable<RSSFeed> items)
        {
            XmlBuilder.Build(filename, document =>
            {
                document.Element("feeds", xItems =>
                {
                    foreach (var item in items)
                    {
                        xItems.Element("feed", xItem =>
                        {
                            xItem["id"] = item.Id.ToString();
                            xItem["name"] = item.Name;
                            xItem["url"] = item.FeedUrl;
                        });
                    }
                });
            });
        }
    }
}
